import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import legacy from "@vitejs/plugin-legacy";
import { resolve } from "path";
import autoprefixer from "autoprefixer";
import commonjs from "vite-plugin-commonjs";
import { visualizer } from "rollup-plugin-visualizer";

// 获取路径
function pathResolve(dir: string) {
  return resolve(__dirname, dir);
}

const targets = [
  "defaults",
  "chrome >= 58",
  "ie >= 11",
  "safari >= 8",
  "ios >= 8",
  "android >= 5",
];

// https://vitejs.dev/config/
export default ({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");
  const { BUILD_TAG, DEV_TAG } = env;
  const publicPath = `[window.__cdn_url_prefix]`;
  const plugins: any = [
    commonjs(),
    vue(),
    // 兼容低浏览器
    legacy({
      targets,
    }),
    // 打包分析
    DEV_TAG === "analyze"
      ? visualizer({
          open: true, // 打包完成后自动打开浏览器，显示产物体积报告
          gzipSize: true, // 收集 gzip 大小并将其显示
          brotliSize: true, // 收集 brotli 大小并将其显示
          filename: "stats.html", // 分析图生成的文件名
        })
      : "",
  ];

  return defineConfig({
    plugins,
    resolve: {
      alias: {
        "@": pathResolve("/src"),
        "@styles": pathResolve("/src/assets/styles"),
        "@images": pathResolve("/src/assets/images"),
        "@apis": pathResolve("/src/apis"),
        "@utils": pathResolve("/src/utils"),
        "@xiaoe/ei18n/i18n": pathResolve("./src/i18n/index.ts"),
      },
    },
    server: {
      port: 3668,
      proxy: {
      },
    },
    // 区分本地启动还是编译，只有编译的时候才需要替换
    base: BUILD_TAG === "build" ? publicPath : "/",
    build: {
      cssCodeSplit: true,
      chunkSizeWarningLimit: 10000,
      rollupOptions: {
        input: "src/main.ts",
        external: [],
        output: {
          format: "es",
          dir: "dist",
          manualChunks(id) {
            if (id.includes("node_modules")) {
              // 根据模块路径分割第三方库
              const module = id.split("node_modules/.pnpm/")[1].split("/")[0];
              return `${module}-chunk`; // 返回的字符串将作为chunk的名称
            }
          },
          chunkFileNames(info) {
            // 语言包需要放到locales/语言/文件夹下，其余可自定义
            const lang = info.facadeModuleId?.match(
              /locales\/([a-zA-Z-_]+)\/(.*)\.json$/
            )?.[1];
            if (lang) {
              return `locales/${lang}/[name]-[hash:6].js`;
            }
            return "js/[name]-[hash:6].js";
          },
          assetFileNames: `[ext]/[name]-[hash:4].[ext]`,
        },
      },
    },
    css: {
      postcss: {
        plugins: [
          autoprefixer({
            // 指定目标浏览器
            overrideBrowserslist: targets,
          }),
        ],
      },
    },
  });
};
